// 验证token
// utils/checkToken.js
const jwt = require("../config/jwt");

//不需要token的路径
const router = [
    '/api/login/login',
    '/api/blog/addBlogImg',
    '/api/blog/getBlogTextList',
    '/api/blog/getBlogTextOne',
    '/api/blog/setViewCount',
    '/api/users/adduser',
    '/api/users/getUserOne',
    '/api/users/retrievePassword',
    '/api/blog/getBlogTypeAll',
    '/api/blog/inquireBlogComment',
    '/api/blog/getBlogCommentList',
    '/api/personalCircle/inquirePersonalCircleDateList',
    '/api/messageBoard/getMessage',
    '/api/dataStatistic/getDataStatistic',
    '/api/dataStatistic/getDataPageViewCount',
    '/api/dataStatistic/StatisticalSex',
]
// 不需要token的后缀
const rotter = ['png', 'jpg', 'mp3', 'webp']
const checkToken = async (ctx, next) => {
    const url = ctx.request.url;
    if (rotter.includes(url.split('.')[1])) {
        await next()
        return
    }
    if (router.includes(url)) {
        await next();
    } else {
        let token = ''
        if (ctx.request.header.authorization) {
            token = ctx.request.header.authorization.split('Bearer ')[1];
        } else {
            ctx.log4js.info('路径:' + ctx.url + '/信息:拒绝访问/参数:' + JSON.stringify(ctx.request.body))
            ctx.body = {
                status: 40001,
                message: '接口拒绝访问'
            };
            return
        }
        if (token) {
            try {
                const payload = await jwt.verify(token);
                const date = new Date().getTime();
                if ((payload.exp * 1000) > date) {
                    await next();
                } else {
                    ctx.log4js.info('路径:' + ctx.url + '/信息:令牌已过期,请重新登录/参数:' + JSON.stringify(ctx.request.body))
                    ctx.body = {
                        status: 40002, message: '令牌已过期,请重新登录'
                    };
                }
            } catch (error) {
                if (error.message === 'jwt expired') {
                    ctx.log4js.info('路径:' + ctx.url + '/信息:令牌已过期,请重新登录/参数:' + JSON.stringify(ctx.request.body))
                    ctx.body = {
                        status: 40002, message: '令牌已过期,请重新登录'
                    };
                }
            }
        } else {
            ctx.log4js.info('路径:' + ctx.url + '/信息:该用户未授权/参数:' + JSON.stringify(ctx.request.body))
            ctx.body = {
                status: 40003, message: '该用户未授权'
            };
        }

    }
};

module.exports = checkToken;
